package cn.jsj.onclock.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.Serializable;

/**
 * @author 卢斌
 */
@Slf4j
@Component
public class WebSocketHandler extends TextWebSocketHandler {

    private final RedisTemplate<String, Serializable> redisTemplate;

    @Autowired
    public WebSocketHandler(RedisTemplate<String, Serializable> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 建立连接后，返回established，表示握手成功
        session.sendMessage(new TextMessage("established"));

        // 将该会话加入到自定义容器中
        WebSocketManager.add(session.getAttributes().get("userId").toString(), session);
    }


    @Override
    @SuppressWarnings("NullableProblems")
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        if (Boolean.TRUE.equals(redisTemplate.hasKey(session.getAttributes().get("token").toString()))) {
            // 获得客户端传来的消息
            String payload = message.getPayload();
            session.sendMessage(new TextMessage(payload));
        } else {
            WebSocketManager.removeAndClose(session.getAttributes().get("userId").toString());
        }
    }



    @Override
    @SuppressWarnings("NullableProblems")
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        redisTemplate.delete(session.getAttributes().get("token").toString());
        WebSocketManager.removeAndClose(session.getAttributes().get("userId").toString());
    }

}
